#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "s5p6818_gpio.h"

//硬件连接
//GPH0_1	LED4
//GPH0_2	LED5
//GPH0_3	LED6
char *dev_file[3]={"/dev/gpioA","/dev/gpioB","/dev/gpioB"};
static int open_dev(const char *devname)
{
	int fd = -1;
	
	fd = open(devname, O_RDWR);
	if(fd < 0)
	{
		perror("open_dev");
		_exit(-1);
	}
	return fd;
}

//led == 1：控制第一个LED
//led == 2：控制第二个LED
//led == 3：控制第三个LED
//flag == 0：灯灭
//flag == 1：灯亮
void led_control(int led, int flag)
{
	int gpio_fd_1 = 0;
	int gpio_fd_2 = 0;
	unsigned int led_status_1_old = 0;
	unsigned int led_status_1_new = 0;
	unsigned int led_status_2_old = 0;
	unsigned int led_status_2_new = 0;
	unsigned int led_status_3_old = 0;
	unsigned int led_status_3_new = 0;
	

	
	//printf("led_status_old = %#x\n", led_status_old);
	switch(led)
	{
		case 1:
			gpio_fd_1 = open_dev("/dev/gpioB");
			ioctl(gpio_fd_1,S5P_GPIO_SET_INPUT,26);
			read(gpio_fd_1, &led_status_1_old, sizeof(led_status_1_old));
			if(flag == 1)
			{
				led_status_1_new =led_status_1_old &(~(0x01<<26));
			}
			else if(flag == 0)
			{
				led_status_1_new = led_status_1_old | (0x01<<26);
			}
			ioctl(gpio_fd_1,S5P_GPIO_SET_OUTPUT,26);
			write(gpio_fd_1, &led_status_1_new, sizeof(led_status_1_new));
			break;
		case 2:
			gpio_fd_2 = open_dev("/dev/gpioC");
			ioctl(gpio_fd_2,S5P_GPIO_SET_INPUT,11);
			read(gpio_fd_2, &led_status_2_old, sizeof(led_status_2_old));
	
			if(flag == 1)
			{
				led_status_2_new = led_status_2_old & (~(0x01<<11));
			}
			else if(flag == 0)
			{
				led_status_2_new = led_status_2_old | (0x01<<11);
			}
		
			ioctl(gpio_fd_2,S5P_GPIO_SET_OUTPUT,11);
			write(gpio_fd_2, &led_status_2_new, sizeof(led_status_2_new));
			break;
		case 3:
			gpio_fd_2 = open_dev("/dev/gpioC");
			ioctl(gpio_fd_2,S5P_GPIO_SET_INPUT,7);
			read(gpio_fd_2, &led_status_3_old, sizeof(led_status_3_old));
	
			if(flag == 1)
			{
				led_status_3_new = led_status_3_old & (~(0x01<<7));
			}
			else if(flag == 0)
			{
				led_status_3_new = led_status_3_old | (0x01<<7);
			}
		
			ioctl(gpio_fd_2,S5P_GPIO_SET_OUTPUT,7);
			write(gpio_fd_2, &led_status_3_new, sizeof(led_status_3_new));
			break;
	}
	close(gpio_fd_1);
	close(gpio_fd_2);
}

